package com.walter.blog.aop.aop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.walter.blog.aop.annotation.NeedLogin;
import com.walter.constant.CookieConstant;
import com.walter.constant.SessionConstant;
import com.walter.db.mapper.UserMapper;
import com.walter.db.pojo.User;
import com.walter.response.ResponseKit;
import com.walter.util.MD5Util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 登录权限验证
 *
 * @author wuchenxi
 * @date 2020-08-12 16:09:34
 */
@Aspect
@Component
public class LoginAop {

    @Resource
    private HttpSession session;

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private UserMapper userMapper;

    @Pointcut("@annotation(com.walter.blog.aop.annotation.NeedLogin)")
    public void point() {
    }

    @Around("point()")
    public Object before(ProceedingJoinPoint joinpoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinpoint.getSignature();
        NeedLogin annotation = signature.getMethod().getAnnotation(NeedLogin.class);
        if (annotation == null) {
            return joinpoint.proceed();
        }

        Object attribute = session.getAttribute(SessionConstant.USER);
        if (attribute == null) {

            boolean isRememberMe = checkIsRememberMe();

            if (!isRememberMe) {
                return ResponseKit.error(HttpStatus.UNAUTHORIZED.value(), "用户还未登录");
            }
        }

        return joinpoint.proceed();
    }

    public boolean checkIsRememberMe() {
        Cookie[] cookies = httpServletRequest.getCookies();
        for (Cookie cookie : cookies) {
            if (Objects.equals(cookie.getName(), CookieConstant.REMEMBER_ME)) {
                String account = cookie.getValue().split("##")[0];
                String password = cookie.getValue().split("##")[1];
                User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .eq(User::getAccount, account));

                if (user == null) {
                    return false;
                }

                if (Objects.equals(MD5Util.md5(user.getPassword()), password)) {
                    session.setAttribute(SessionConstant.USER, user);
                    return true;
                }
            }
        }
        return false;
    }

}
